<template>
  <div class="app-container mylot">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="搜索专场" style="width: 300px;margin-right: 10px;" @keyup.enter.native="handleFilter">
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加专场</el-button>
      <el-popover width="160" placement="right" trigger="click">
        <img style="width: 100%;" :src="mobileQr" alt="">
        <el-button slot="reference" type="primary">在手机上查看专场</el-button>
      </el-popover>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
    >
      <el-table-column align="center" label="ID" prop="id" width="60" />
      <el-table-column show-overflow-tooltip align="center" label="专场名称" prop="name" width="210" />
      <el-table-column align="center" label="专场时间" prop="time" width="280">
        <template slot-scope="scope">
          {{ scope.row.time_format[0] === scope.row.time_format[1] ? scope.row.time_format[0] : scope.row.time_format.join(' ~ ') }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="汇率" prop="rate" width="70" />
      <el-table-column show-overflow-tooltip align="center" label="专场备注" prop="remark" width="230" />
      <el-table-column align="center" label="查看拍品" prop="num" width="90">
        <template slot-scope="scope">
          <el-button type="text" @click="$router.push(`/${scope.row.id}`)">{{ scope.row.num }} 件</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="控制" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.show"
            active-text="显示"
            inactive-text="隐藏"
            @change="handleSwitch(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="210">
        <template slot-scope="scope">
          <el-button-group>
            <el-button type="warning" size="mini" @click="handleSet(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDel(scope.row)">删除</el-button>
            <el-button type="warning" size="mini" @click="handleEmpty(scope.row)">清空</el-button>
            <!-- <el-button type="primary" size="mini" @click="handleGoods(scope.row)">拍品</el-button> -->
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="total > 0" class="pagination-container">
      <el-pagination background :current-page="listQuery.page" :page-sizes="[15, 20, 30]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" top="10vh" center :visible.sync="dialogFormVisible" @closed="handleDialogClose">
      <el-form ref="lotForm" class="form-goods" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-form-item v-if="dialogStatus === 'edit'" hidden label="专场ID" prop="id">
          <el-input v-model.trim="temp.id" disabled />
        </el-form-item>
        <el-form-item label="专场封面">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            accept="image/*"
            action="api"
            :show-file-list="false"
            :file-list="coverList"
            :on-change="handleThumbChange"
            list-type="picture-card"
          >
            <img v-if="temp.cover" :src="temp.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">大小不超过500kb，如需更改，点击重新选择图片即可</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="专场名称" prop="name">
          <el-input v-model.trim="temp.name" />
        </el-form-item>
        <el-form-item label="专场时间" prop="time">
          <el-date-picker
            v-model="temp.time"
            type="datetimerange"
            style="width: 100%; max-width: 550px"
            value-format="timestamp"
            format="yyyy-MM-dd HH:mm"
            range-separator="至"
            start-placeholder="专场开始时间"
            end-placeholder="专场结束时间"
          />
        </el-form-item>
        <el-form-item label="显示隐藏" prop="state">
          <el-switch
            v-model="temp.show"
            active-text="显示"
            inactive-text="隐藏"
          />
        </el-form-item>
        <el-form-item label="专场汇率" prop="rate">
          <el-input v-model.trim="temp.rate" type="number" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="temp.remark" type="textarea" :autosize="{ minRows: 1, maxRows: 2 }" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button :loading="btnLoading" type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLots, setLot, delLot, emptyLot } from '@/api/lot'
import { parseTime } from '@/utils/index'
export default {
  data () {
    return {
      listQuery: {
        page: 1,
        limit: 15,
        name: ''
      },
      list: [],
      total: 0,
      mobileQr: '',
      listLoading: true,
      lotData: new FormData(),
      temp: {
        id: '',
        cover: '',
        name: '',
        time: '',
        show: '',
        rate: '',
        remark: ''
      },
      dialogStatus: '',
      textMap: {
        edit: '修改专场信息',
        add: '添加专场'
      },
      rules: {
        name: [{ required: true, message: '专场名称不能为空', trigger: 'blur' }],
        time: [{ required: true, message: '专场时间不能为空', trigger: 'blur' }],
        remark: [{ required: true, message: '专场备注不能为空', trigger: 'blur' }]
      },
      coverList: [],
      dialogFormVisible: false,
      btnLoading: false
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.listLoading = true
      getLots(this.listQuery).then(res => {
        res.data.list.forEach(el => {
          el.time_format = [parseTime(el.time[0], '{y}-{m}-{d} {h}:{i}'), parseTime(el.time[1], '{y}-{m}-{d} {h}:{i}')]
        })
        this.list = res.data.list
        this.total = res.data.total
        this.mobileQr = res.data.mobile_qr
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleAdd () {
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.temp = {
        name: '',
        time: '',
        show: true,
        remark: '',
        cover: ''
      }
      this.$nextTick(() => {
        this.$refs['lotForm'].clearValidate()
      })
    },
    handleSet (row) {
      this.dialogStatus = 'edit'
      this.temp = JSON.parse(JSON.stringify(row))
      this.coverList = [{ url: row.cover }]
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['lotForm'].clearValidate()
      })
    },
    handleDel (row) {
      this.$confirm('确定要删除该专场吗？', {
        type: 'warning'
      }).then(() => {
        delLot(row.id).then(res => {
          this.$message.success(res.msg)
          this.fetchData()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },
    handleEmpty (row) {
      this.$confirm('确定要清空该专场所有拍品吗？', {
        type: 'warning'
      }).then(() => {
        emptyLot(row.id).then(res => {
          this.$message.success(res.msg)
          this.fetchData()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },

    handleThumbChange (file, fileList) {
      const isLt = file.size / 1024 / 1024 < 0.5
      if (!isLt) {
        // fileList = []
        this.$message.error('上传拍品缩略图大小不能超过 500kb!')
      } else {
        this.lotData.set('cover', file.raw)
        this.temp.cover = URL.createObjectURL(file.raw)
      }
    },
    handleSubmit () {
      Object.keys(this.temp).forEach(key => {
        if (key !== 'cover') {
          this.lotData.set(key, this.temp[key])
        }
      })
      this.$refs['lotForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          setLot(this.lotData).then(res => {
            res.data.time_format = [parseTime(res.data.time[0], '{y}-{m}-{d} {h}:{i}'), parseTime(res.data.time[1], '{y}-{m}-{d} {h}:{i}')]
            if (this.dialogStatus === 'add') {
              this.list.unshift(res.data)
            } else {
              const index = this.list.findIndex(el => Number(el.id) === Number(this.temp.id))
              this.list.splice(index, 1, res.data)
            }
            this.dialogFormVisible = false
            this.btnLoading = false
            this.lotData = new FormData()
            this.coverList = []
            this.$notify({
              message: res.msg,
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            this.btnLoading = false
            console.log(err)
          })
        }
      })
    },
    handleDialogClose () {
      this.lotData = new FormData()
      this.coverList = []
    },
    handleSwitch (row) {
      var data = new FormData()
      Object.keys(row).forEach(key => {
        if (key !== 'cover') {
          data.set(key, row[key])
        }
      })
      setLot(data).then(res => {
        this.$notify({
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      }).catch(err => {
        const index = this.list.findIndex(el => Number(el.id) === Number(row.id))
        row.show = !row.show
        this.list.splice(index, 1, row)
        console.log(err)
      })
    },
    handleFilter () {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleGoods (row) {
      this.$router.push(`/${row.id}`)
    }
  }
}
</script>

<style lang="scss">
.el-table {
  width: fit-content;
  margin-bottom: 20px;
  .ing-row {
    background: rgb(243, 218, 210);
  }
}
.mylot {
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #009788;
      }
    }
    &-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
    }
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
  .el-upload__tip{
    line-height: 20px;
    margin-top: 5px;
  }
}
</style>
